import { defineStore } from 'pinia';
import { computed, ref, watch } from 'vue';
import { DeviceInfoApi } from '@/api/common/deviceInfo';
import { useDeviceMqtt } from '@/hooks/useDeviceMqtt';
import { useDeviceSetting } from '@/hooks/useDeviceSetting';
import { ls } from '@/utils/ls.utils';
import { isH5 } from '@/utils/platform.utils';

export const useDeviceStore = defineStore('device', () => {
  const { deviceInfo, connect, onMessage, publish, isConnected, updateConfig } = useDeviceMqtt();

  const { dispatchHandler } = useDeviceSetting();

  onMessage(res => {
    const message = res.message;
    setDeviceAttrs(message);
    dispatchHandler(message);
  });

  const connectDevice = () => {
    DeviceInfoApi.getDeviceInfo(deviceCode.value).then(res => {
      deviceInfo.value = res;
      connect();
    });
  };

  // TODO
  const deviceCode = ref<string>(ls.get('deviceCode', 'ZZZDJ001'));

  const getDeviceCode = () => {
    return deviceCode.value;
  };

  const setDeviceCode = (code: string) => {
    if (!code) {
      return;
    }
    deviceCode.value = code;
    ls.set('deviceCode', code);
    connectDevice();
  };

  const deviceAttrs = ref({
    // 语音播报次数
    speakTimes: 2,
    // 滚动速度
    scrollSpeed: 1,
    // 亮度
    brightness: 50,
    // 通话音量
    volumeCall: 5,
    // 提示音量
    volumeTip: 5,
    // 媒体音量
    volumeMedia: 5,
    // 息屏时间
    screenOffTime: [],
    // 服务器地址
    serverUrl: import.meta.env.VITE_SERVER_BASEURL,
    // websocket地址
    websocketUrl: import.meta.env.VITE_WEBSOCKET_PATH,
    // MQTT地址
    mqttUrl: import.meta.env.VITE_MQTT_PATH
  });

  const setDeviceAttrs = (attrs: Partial<typeof deviceAttrs.value>) => {
    deviceAttrs.value = {
      ...deviceAttrs.value,
      ...attrs
    };
    publish(attrs);
  };

  const buildRequestBaseURL = () => {
    return isH5 && JSON.parse(import.meta.env.VITE_APP_PROXY)
      ? import.meta.env.VITE_APP_PROXY_PREFIX
      : deviceAttrs.value.serverUrl;
  };

  const buildWebsocketUrl = computed(() => {
    return `${deviceAttrs.value.websocketUrl}/healthcare/ws?deviceCode=${deviceCode.value}`;
  });

  watch(() => deviceAttrs.value.mqttUrl, url => {
    if (url) {
      updateConfig({
        brokerUrl: url
      });
    }
  });

  const setupDevice = () => {
    if (deviceCode.value && !isConnected.value) {
      connectDevice();
    }
  };

  return {
    deviceInfo,

    deviceCode,
    setDeviceCode,
    getDeviceCode,

    deviceAttrs,
    setDeviceAttrs,
    setupDevice,

    buildRequestBaseURL,
    buildWebsocketUrl
  };
});
